package org.cweili.vehicle.service.admin

import org.cweili.vehicle.entity.Vehicle
import org.cweili.vehicle.service.BaseService
import org.cweili.vehicle.util.Const
import org.cweili.vehicle.util.JSON
import org.cweili.vehicle.util.Utils
import org.directwebremoting.annotations.RemoteProxy
import org.directwebremoting.spring.SpringCreator
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service

import com.alibaba.fastjson.JSONArray

/**
 * 管理员车辆服务
 *
 * @author Cweili
 * @version 2013年7月27日 下午11:24:22
 *
 */
@RemoteProxy(creator = SpringCreator.class)
@Service
class AdminVehicleService extends BaseService {

	Page<Vehicle> getList(String json) {
		def obj = JSON.parseObject(json)

		def type = JSON.getByte(obj, "type")
		def page = JSON.getInteger(obj, "page")

		return vehicleRepository.findByClassification(type, new PageRequest(page, Const.PAGE_SIZE,
		Sort.Direction.DESC, "id"))
	}

	boolean del(String json) {
		try {
			def array = JSONArray.parseArray(json)

			for (obj in array) {
				vehicleRepository.delete(Integer.parseInt(obj.toString()))
			}
		} catch (Exception e) {
			log.error(e + json, e)
			return false
		}
		return true
	}

	boolean save(String json) {
		def obj = JSON.parseObject(json)

		def classification = JSON.getByte(obj, "classification")
		def id = JSON.getInteger(obj, "id")
		def priceString = JSON.getString(obj, "price")
		def licensePlate = JSON.getString(obj, "licensePlate")
		def model = JSON.getString(obj, "model")
		def frameNumber = JSON.getString(obj, "frameNumber")
		def engineNumber = JSON.getString(obj, "engineNumber")
		def registrationDate = JSON.getDate(obj, "registrationDateYear", "registrationDateMonth",
				"registrationDateDate")
		def buyDate = JSON.getDate(obj, "buyDateYear", "buyDateMonth", "buyDateDate")

		if (Utils.isEmpty(licensePlate)) {
			return false
		}

		def vehicle
		if (id > 0) {
			vehicle = vehicleRepository.findOne(id)
			if (!vehicle) {
				return false
			}
		} else {
			vehicle = new Vehicle()
		}
		vehicle.buyDate = buyDate
		vehicle.classification = classification
		vehicle.engineNumber = engineNumber
		vehicle.frameNumber = frameNumber
		vehicle.licensePlate = licensePlate
		vehicle.model = model
		vehicle.price = Utils.stringToMoney(priceString)
		vehicle.registrationDate = registrationDate
		return vehicleRepository.save(vehicle)
	}
}
